#include "timer.h"

static u64 timer_10ms_count = 0;

static TIMER_STRUCT timer_handler[TIMER_NUM];

void Delay_Ms(u32 nTime)
{
	u32 i=0;
	nTime = nTime*1000;
	while(nTime--)
	{
		i=10;
		while(i--);
	}
}

void Delay_Us(u32 nTime)
{
	u16 i=0;
	while(nTime--)
	{
		i=10;
		while(i--);
	}
}


int timer_update_IT(void)
{
    static u64 times = 0;
    u8 i = 0;
    TIMER_CB pFun;

    timer_10ms_count++;

    for(i = 0; i < TIMER_NUM; i++)
    {
        if(L_TRUE == timer_handler[i].isStart && timer_10ms_count > timer_handler[i].count)
        {
            timer_handler[i].isStart = L_FALSE;
            if(timer_handler[i].pFun)
            {
                pFun = timer_handler[i].pFun;
                timer_handler[i].pFun = NULL;
                pFun();
            }
        }
    }
    times++;
    
    return F_SUCCESS;
}

int timer_start(TIMER_ENUM id, u32 period, TIMER_CB pFun)
{
    timer_handler[id].count = timer_10ms_count + period / 10;
    timer_handler[id].pFun = pFun;
    timer_handler[id].isStart = L_TRUE;
    return F_SUCCESS;
}

int timer_stop(TIMER_ENUM id)
{
    timer_handler[id].isStart = L_FALSE;
    return F_SUCCESS;
}

int timer_isTimerStart(TIMER_ENUM id)
{
    return timer_handler[id].isStart;
}

int timer_isSleep(void)
{
    for(int i = 0; i < TIMER_NUM; i++)
    {
        if(L_TRUE == timer_isTimerStart((TIMER_ENUM)i))
        {
            return L_FALSE;
        }
    }
    return L_TRUE;
}


